﻿#include "mainwindow.h"
#include "dashboardwidget.h"

#include <QtWidgets>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
    currentSpeed(0),
    timer(new QTimer(this))
{
    rabbitLabel = new QLabel(this);
    rabbitImages[0].load(":/images/rabbit_leg1.png");
    rabbitImages[1].load(":/images/rabbit_leg2.png");
    rabbitImages[2].load(":/images/rabbit_leg3.png");
    rabbitImages[3].load(":/images/rabbit_leg4.png");
    rabbitImages[4].load(":/images/rabbit_leg5.png");
    // 创建表盘
    DashBoardWidget *dashBoardWidget = new DashBoardWidget(this);
    dashBoardWidget->setUnit("m/s");
    dashBoardWidget->setText("速度");
    dashBoardWidget->setValue(currentSpeed);

    // 创建滑块
    QSlider *slider = new QSlider(Qt::Horizontal, this);
    slider->setRange(0, 100);
    slider->setValue(currentSpeed);

    // 创建按钮
    QPushButton *btnAccelerate = new QPushButton("加速", this);
    QPushButton *btnDecelerate = new QPushButton("减速", this);

    // 布局
    QWidget *widget = new QWidget(this);
    QHBoxLayout *layout = new QHBoxLayout(widget);
    layout->addWidget(dashBoardWidget);
    layout->addWidget(rabbitLabel);
    layout->addWidget(slider);
    layout->addWidget(btnAccelerate);
    layout->addWidget(btnDecelerate);
    setCentralWidget(widget);
    // 布局中添加 rabbitLabel


    // 连接信号和槽
    connect(slider, &QSlider::valueChanged, dashBoardWidget, &DashBoardWidget::setValue);
    connect(btnAccelerate, &QPushButton::clicked, this, &MainWindow::accelerate);
    connect(btnDecelerate, &QPushButton::clicked, this, &MainWindow::decelerate);
    connect(timer, &QTimer::timeout, this, &MainWindow::updateSpeed);
    connect(this, &MainWindow::speedChanged, dashBoardWidget, &DashBoardWidget::setValue);

    // 设置定时器
    timer->start(100);
    resize(600, 400);
}

MainWindow::~MainWindow()
{
}

void MainWindow::accelerate()
{
    if (currentSpeed < 100) {
        currentSpeed=currentSpeed+10;
        emit speedChanged(currentSpeed);
    }
}

void MainWindow::decelerate()
{
    if (currentSpeed > 0) {
        currentSpeed=currentSpeed-10;
        emit speedChanged(currentSpeed);
    }
}



void MainWindow::updateSpeed()
{
    // 更新速度表
    emit speedChanged(currentSpeed);

    // 更新小兔子的腿部动画
    currentImageIndex = (currentImageIndex + 1) % 4;
    rabbitLabel->setPixmap(rabbitImages[currentImageIndex]);
    // 可以根据速度调整动画的快慢
    // 例如，速度越快，定时器间隔越短
    int interval = 300- currentSpeed * 2; // 仅为示例，实际可能需要调整
    if (interval < 100) interval = 100; // 设置最小间隔
    timer->setInterval(interval);
}
